<?php

class Test_Cache_Redis {

    private $_cache = null;

    public function __construct() {
        $this->_cache = Cache::factory('Redis', array(
            'life_time' => 300,
            'servers' => array(
                array(
                    'host' => 'localhost',
                    'port' => 6379,
                    'timeout' => 6,
                ),
            ),
        ));
    }

    /**
     * 测试 存储获取
     * @return type
     */
    public function testSaveLoad() {

        $id = 'test key';
        $val = 'test data #'.time();
        $this->_cache->save($id, $val);
        echo 'set: ', $val, PHP_EOL;
        $val2 = $this->_cache->load($id);
        echo 'get: ', $val2, PHP_EOL;
        return $val2 === $val ? true : false;
    }

    /**
     * 测试自动过期
     * @return type
     */
    public function testExpire() {

        $id = 'test key';
        $val = 'test data #'.time();
        $this->_cache->save($id, $val, 5);
        $maxTry = 10;
        while ($maxTry--) {
            $val2 = $this->_cache->load($id);
            echo 'get: ', $val2, PHP_EOL;
            if (!$val2) {
                return true;
            }
            sleep(1);
        }
        return false;
    }

    /**
     * 测试删除
     * @return type
     */
    public function testDel() {

        $id = 'test key';
        $val = 'test data #'.time();
        $this->_cache->save($id, $val);
        $this->_cache->remove($id);
        return !$this->_cache->load($id) ? true : false;
    }

    /**
     * 测试全部清理
     * @return type
     */
    public function testClean() {

        $id = 'test key';
        $val = 'test data #'.time();
        $this->_cache->save($id, $val);
        $this->_cache->clean($id);
        return !$this->_cache->load($id) ? true : false;
    }
}
